# coding:utf-8
"""
@Version: V1.0
@Author: willson
@License: Apache Licence
@Contact: willson.wu@goertek.com
@Site: goertek.com
@Software: PyCharm
@File: lada.py
@Time: 2019/7/16 18:12
"""

from ldap3 import Connection, SUBTREE, ServerPool

LDAP_SERVER_POOL = ["10.10.40.2"]
LDAP_SERVER_PORT = 389
ADMIN_DN = "xxx@xxx.xxx"
ADMIN_PASSWORD = "xxxxxxx"
SEARCH_BASE = "ou=xxx,dc=xxx,dc=xxx"


def ldap_auth(username, password):
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool, user=ADMIN_DN, password=ADMIN_PASSWORD, check_names=True, lazy=False,
                      raise_exceptions=False)
    conn.open()
    conn.bind()

    res = conn.search(
        search_base=SEARCH_BASE,
        search_filter='(sAMAccountName={})'.format(username),
        search_scope=SUBTREE,
        attributes=['cn', 'givenName', 'mail', 'sAMAccountName'],
        paged_size=5
    )
    print(res)

    if res:
        entry = conn.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']

        # check password by dn
        try:
            conn = Connection(ldap_server_pool, user=dn, password=password, check_names=True, lazy=False,
                              raise_exceptions=False)
            conn.bind()
            if conn.result["description"] == "success":
                print((True, attr_dict["mail"], attr_dict["sAMAccountName"], attr_dict["givenName"]))
                return (True, attr_dict["mail"], attr_dict["sAMAccountName"], attr_dict["givenName"])
            else:
                print("auth fail")
                return (False, None, None, None)
        except Exception as e:
            print("auth fail")
            return (False, None, None, None)
    else:
        return (False, None, None, None)


if __name__ == "__main__":
    # # server = "ldap://10.10.20.2:389"
    server = "ldap://10.10.40.2:389"
    # user = "willson.wu@goertek.com"
    # pwd = "123!@#QWEasdZXC"
    #
    # conn = Connection(server=server, user=user, password=pwd, check_names=True, lazy=False,
    #                    raise_exceptions=False)
    # conn.bind()
    # # DN="OU=Group,OU=Group,DC=it,DC=goertek,DC=com"
    # # print(conn.search(search_base='',search_filter='(objectClass=*)',attributes=['*']))
    # #
    # #
    #
    # print(conn.result)
    # print(conn.request)
    # print(conn.response)
    # print(type(conn), "ssss:", conn)
    # if conn.result["description"] == "success":
    #     print("登录成功")
    # else:
    #     print("登录失败")

    # import json
    #
    # d = {"username": "asd.d"}
    # s = json.dumps(d)

    # headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Mobile Safari/537.36",
    #            "Cookie": "ShaunXu.MvcLocalization.CurrentUICulture = zh - CN",
    #            "Referer":"http://10.10.40.102/Home/CheckIndex",
    #            "Origin":"http://10.10.40.102",
    #            "X-Requested-With":"XMLHttpRequest",
    #            }
    #
    # c = requests.post("http://10.10.40.102/Home/CheckADEmail", data={"username": "asd.d"}, headers=headers)
    # print(c.text)

    # print(a)

    import requests
    import re


